//
//  SinaComposeVCViewController.swift
//  mySina
//
//  Created by 刘莹 on 2016/11/22.
//  Copyright © 2016年 liuying. All rights reserved.
//

import UIKit
import SVProgressHUD

private let baseTag = 10000

//
enum SinaComponesType:Int{
    
    case Picture = 10000
    case AtSome
    case Topic
    case Emotion
    case More
}


class SinaComposeVCViewController: UIViewController {
    
    //MARK: -
    //MARK: - 懒加载
    //发送按钮
    lazy var sendBtn: UIBarButtonItem = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
        //设置文字
        btn.setTitle("发送", for: .normal)
        //设置背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.addTarget(self, action: #selector(sendBtnDidClick), for: .touchUpInside)
        //设置文字颜色
        let barButtonItem = UIBarButtonItem(customView: btn)
        barButtonItem.isEnabled = false
        return barButtonItem
    }()
    
    //textView
    lazy var textView: UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFont(ofSize: 18)
        tv.textColor = UIColor.darkGray
        //textView 没有占位文本
        //tv.text = "我是小王,我为自己带盐"
        //tv.backgroundColor = randomColor()
        tv.delegate = self
        tv.backgroundColor = UIColor(white: 0.9, alpha: 1)
        tv.keyboardDismissMode = .onDrag
        tv.alwaysBounceVertical = true
        return tv
    }()
    //默认文字
    lazy var placeHolderLabel: UILabel = {
        let l = UILabel(title: "我是小王,我为自己带盐", fontSize: 18, textColor: UIColor.lightGray)
        return l
    }()
    //底部工具条
    lazy var toolBar:UIStackView = {
        let bottomBar = UIStackView(frame:CGRect.zero)
        //初始设置:
        //1.设置方向
        bottomBar.axis = .horizontal
        //2.设置填充的方式
        bottomBar.distribution = .fillEqually
        
        return bottomBar
        
    }()
    //图片选择器的控制器
    lazy var selector:SinaPictureSelectorVC = {
    
        let flowlayout = UICollectionViewFlowLayout()
        flowlayout.itemSize = CGSize(width: selectorCellWidth, height: selectorCellWidth)
        //设置行和列的最小间距
            flowlayout.minimumLineSpacing = selectorMargin
        flowlayout.minimumInteritemSpacing = selectorMargin
        //设置组内间距
        flowlayout.sectionInset = UIEdgeInsets(top: selectorMargin, left: selectorMargin, bottom: 0, right: selectorMargin)
        let picSel = SinaPictureSelectorVC(collectionViewLayout: flowlayout)
        //注意:CollectionViewController的根视图是view而不是collectionView
        picSel.view.backgroundColor = UIColor.white
        picSel.collectionView?.backgroundColor = UIColor.white
        return picSel
    }()
    //自定义键盘视图
    lazy var keyboardView:HMEmoticonKeyboardView = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height: 220))
    
    
    
    
    //MARK: -
    //MARK: - 界面将要显示的时候,判断selector时候有图片,是否显示selector.view
    override func viewWillAppear(_ animated: Bool) {
        
        super.viewWillAppear(animated)
        
        selector.view.isHidden = selector.selectedImages.count == 0
    }
    //MARK: -
    //MARK: - viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)
        setNavBar()//设置navigationBar
        setTextView()//设置TextView
        setToolBar()//设置底部工具条
        registerNotifaction()//注册通知
        setSelectorPicture()//设置图片选择器视图
        self.view.bringSubview(toFront: toolBar)//将toolBar移动到最上面
    }
    //MARK: -
    //MARK: - ⭐️1.注册通知(键盘)
    private func registerNotifaction(){
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged(n:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //注册选择表情的通知
        NotificationCenter.default.addObserver(self, selector: #selector(insertEmoticon(n:)), name: NSNotification.Name(KSelectEmoticon), object: nil)
    }
    //MARK: -
    //MARK: - 插入表情
    @objc private func insertEmoticon(n: Notification) {
        print(n)
        //如果用户点击的时候删除按钮的时候 n.object 为nil
        guard let em = n.object as? HMEmoticon else {
            //点击的是删除按钮
            //执行回删
            textView.deleteBackward()
            return
        }
        //如果用户点击的时候emoji表情
        if em.type == 1 {
            //emoji表情 将emoji表情插入到光标选择的位置
            textView.replace(textView.selectedTextRange!, withText: em.emojiStr ?? "")
            return
        }
        
        //最后就需要处理表情图片  比较难
        //程序走到这里 一定是表情图片
        
        //2. 通过附件对象实例化属性字符串
        //1. 实例化附件对象 ,将图片包装到附件对象中  attachment
       // let attachment = NSTextAttachment()
        let attachment = HMTextAttachment()
        attachment.chs = em.chs
        let lineHeight = textView.font!.lineHeight
        //frame 是相对父控件的 bounds相对于自己的  scrollView能够滚动实际上修改的是自己的bounds,contentOffset 实际上就是 bounds.origin
        attachment.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
        attachment.image = UIImage(named: em.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)
        //2. 通过附件对象实例化一个 可变的属性字符串 (后面需要给它添加属性) imageText
        let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        //2.1 需要给附件属性文本添加属性
        imageText.addAttributes([NSFontAttributeName : textView.font!], range: NSRange(location: 0, length: 1))
        //3. 获取当前文本输入视图可变的属性字符串 strM
        let strM = NSMutableAttributedString(attributedString: textView.attributedText)
        //3.1 在替换属性文本 之前 线记录光标选中的位置
        let range = textView.selectedRange
        //4. 将 imageText 替换到strM 对应的光标位置
        strM.replaceCharacters(in: textView.selectedRange, with: imageText)
        //5. 将strM赋值给 textView.attributedText
        textView.attributedText = strM
        
        //6. 将光标恢复到之前选中的位置
        textView.selectedRange = NSRange(location: range.location + 1, length: 0)
        //输入图片的时候无法调用代理方法 手动调用
        textView.delegate?.textViewDidChange?(textView)
        
    }
    //MARK: -
    //MARK: - ⭐️2.监听键盘变化的通知
    @objc private func keyboardChanged(n:Notification){
//       print("-----")
//        print(n)
        let endFrame = (n.userInfo![UIKeyboardFrameEndUserInfoKey]as! NSValue).cgRectValue
        //让底部toolbar能够移动
        //修改底部的约束
        let offsetY = -(ScreenHeight - endFrame.origin.y)
        //更新约束
      UIView.animate(withDuration: 0.25) {
        
            self.toolBar.snp.updateConstraints({ (make) in
                make.bottom.equalTo(self.view).offset(offsetY)
                
            })
            self.view.layoutIfNeeded()
        }
    }
    //MARK: -
    //MARK: - 关闭
    @objc internal func close() {
        dismiss(animated: true, completion: nil)
    }
    //MARK: -
    //MARK: - 发送按钮点击事件
    @objc private func sendBtnDidClick(){
        //需要将文本中的表情图片转换为chs 发送到服务器
        //        print(textView.text)
        //        print("==================")
        //        print(textView.attributedText)
        //如果属性文本中包含图片 属性中就会包含NSAttachment这个key会对应一个附件对象
        
        //遍历文本的属性
        var strM = String()
        textView.attributedText.enumerateAttributes(in: NSMakeRange(0, textView.attributedText.length), options: [], using: { (dict,range,_) -> () in
            print(dict)
            print("=========")
            print(NSStringFromRange(range))
            if let attachment = dict["NSAttachment"] as? HMTextAttachment {
                //图片
                print(attachment.chs)
                strM += attachment.chs ?? ""
            } else {
                //文字或者emoji
                let sub = (self.textView.text as NSString).substring(with: range)
                strM += sub
            }
        })
        
        print(strM)

        
        
        
        
    
    
    }
    //MARK: -
    //MARK: - 底部工具条按钮的点击事件
    internal func toolbarButtonClick(btn:UIButton){
        
        let enumType = SinaComponesType(rawValue: btn.tag)!
        switch enumType {
        case .Picture:
            //print("选择图片")
            selector.userWillChosePic(cell: nil)
        case .AtSome:
            print("@某人")
        case .Topic:
            print("话题")
        case .Emotion:
            //print("表情")
            //设置自定义视图和系统默认键盘
            //print("--\(textView.inputView)")
            textView.inputView = textView.inputView == nil ? keyboardView:nil
            //如果当前输入视图不是第一响应者就成为第一响应者
            if !textView.isFirstResponder{
            
                textView.becomeFirstResponder()
            }
            //刷新输入视图
            textView.reloadInputViews()
        case .More:
            print("更多")
        }
        
        
    }
    //MARK: -
    //MARK: - ⭐️3.移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}


extension SinaComposeVCViewController: UITextViewDelegate {
    //MARK: -
    //MARK: - 监听textView被点击事件
    func textViewDidChange(_ textView: UITextView) {
        //判断发布微博按钮的状态
        sendBtn.isEnabled = textView.hasText
        
        //占位文本需要隐藏
        placeHolderLabel.isHidden = textView.hasText
    }
}


//MARK: 设置UI界面
extension SinaComposeVCViewController {
    
    //MARK: -
    //MARK: - 设置textView
    func setTextView() {
        //添加子视图
        self.view.addSubview(textView)
        //添加占位文本
        self.textView.addSubview(placeHolderLabel)
        
        //实例化textView控件 添加约束
        textView.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            //添加高度约束
            make.height.equalTo(ScreenHeight / 3)
        }
        
        placeHolderLabel.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
        
        //设置占位文本的约束
    }
    //MARK: -
    //MARK: - 设置navgationBar
    func setNavBar() {
        //        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭",target: self, action: #selector(close))
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.plain, target: self, action: #selector(close))
        //设置日发布按钮
        self.navigationItem.rightBarButtonItem = sendBtn
        //设置导航条文字
        //属性文本
        
        let titleLabel = UILabel()
        titleLabel.textAlignment = .center
        titleLabel.numberOfLines = 0
        if let userName = SinaUserAccountViewModel.shared.userAccount?.name {
            let titleText = "发布微博\n\(userName)"
            titleLabel.text = titleText
            //修改属性文本的属性 使用可变的属性文本 (添加属性), 不可变的属性文本是不能够添加属性的
            let strM = NSMutableAttributedString(string: titleText)
            //获取用户名的范围
            let range = (titleText as NSString).range(of: userName)
            //给用户名添加属性
            strM.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 13), NSForegroundColorAttributeName : UIColor.orange], range: range)
            //给label的属性文本赋值
            titleLabel.attributedText = strM
        } else {
            titleLabel.text = "发布微博"
        }
        
        titleLabel.sizeToFit()
        self.navigationItem.titleView = titleLabel
    }
    //MARK: -
    //MARK: - 设置底部工具条
    func setToolBar(){
        
        self.view.addSubview(toolBar)
        //设置约束
        toolBar.snp.makeConstraints { (make) in
            
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(40)
        }
        toolBar.backgroundColor = UIColor.red
        
        //添加按钮
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        for (index,imageName) in imageNames.enumerated() {
            
            let btn = UIButton()
            btn.setImage(UIImage(named:imageName), for: UIControlState.normal)
            btn.backgroundColor = UIColor(white: 0.96, alpha: 1)
            btn.sizeToFit()
            //添加到toolBar
            toolBar.addArrangedSubview(btn)
            //添加按钮的点击事件
            btn.addTarget(self, action: #selector(toolbarButtonClick(btn:)), for: .touchUpInside)
            btn.tag = index + baseTag
        }
        
    }
    //MARK: -
    //MARK: - 设置图片选择器
    func setSelectorPicture(){
    
        self.addChildViewController(self.selector)
        self.view.addSubview(selector.view)
        
        selector.view.snp.makeConstraints { (make) in
            
            make.bottom.left.right.equalTo(self.view)
            make.height.equalTo(ScreenHeight/3*2)
            
        }
    }
}
